<?php
namespace app\controller\model\apis;

use app\BaseController;
use app\controller\model;
use GuzzleHttp\Client;
use think\facade\Db;
class Tuanyou extends BaseController
{
	public $urlTest="";
	public $develop=true;
	public $apiUrl="";
	protected $url='',$appKey,$secret,$supplierCode,$tables,$token,$mobile;
	public $supplier;
	public $data;
	protected $header=["Content-Type" => "application/json"];
    public function __construct($supplier=[]){
	    $this->tables = new model\Tables();
		$this->start($supplier);
    }
	//团油需要的接口

	/**退款成功通知接口
	 * @return void
	 */
	public function applyRefund($post){
		try {
			//接收上游订单处理通知
			$this->data = $post;
			if(!is_array($post)) $this->data = json_decode($post,true);

			if($this->data){
				$sign = $this->data['sign'];
				$this->mkSign();
				if($sign != $this->data['sign']){
					$this->data['sign2']=$sign;
					w_log(0,"团油返回".$this->supplier['id'],"签名错误",'tuan/applyRefund',json_encode($this->data));
					return '签名错误';
				}
				return $this->data;
			}else{
				w_log(0,"团油返回".$this->supplier['id'],"数据错误",'tuan/applyRefund',json_encode($this->data));
				return '数据错误:2';
			}
		}catch (\Exception $e){
			w_log(0,"团油返回".$this->supplier['id'],"内部错误",'tuan/applyRefund',$e.error_get_last());
			return '内部错误';
		}
	}

	//团油异步接口结束
	public function test(){
		$this->setData();
		$this->data['token']=$this->supplier['token'];
		$re = $this->sendUrl('gasws/gasBrand');
		var_dump($re);
		if(isset($re['code']) && $re['code']==200){
			return true;
		}
		return false;
	}
	//加油的所有接口
	//由于是本地确认后才下单的 所以所有已下单的都是已付款的  所以取消直接退款
	/**取消加退款订单
	 * @param $supplier_no
	 * @return bool
	 */
	public function cancelOrder($order){
		return $this->returnPay($order);
	}
	public function cancelOrder2($supplier_no){//团油取消订单  没付款之前可以取消
		$this->setData();
		$this->data['orderId']=$supplier_no;
		$this->data['token']=$this->supplier['token'];
		$re = $this->sendUrl('orderws/cancelOrder');
		if(isset($re['code']) && $re['code']==200){
			return true;
		}
		return false;
	}
	public function returnPay($order){
		$this->setData();
		$this->data['token']=$this->supplier['token'];
		$this->data['orderSn']=$order['o_pay_no'];
		$this->data['orderId']=$order['supplier_no'];
		$this->data['refundAmount']=bcmul($order['o_amountPay'],100);
		$this->data['outOrderId']=isset($order['order_no'])?$order['order_no']:$order['service_no'];
		$re = $this->sendUrl('orderws/applyRefund');
		if(isset($re['code']) && $re['code']==200){
			return $re['result'];
		}
		return false;
	}
	public function mkOrder($order){
		$this->setData();
		if(!isset($order['order_no']) || strlen($order['order_no'])<1){
			$order['order_no'] = $order['service_no'];
		}
		$gas = DB::name($this->tables->gas)->where("id",$order['gasID'])->find();
		$this->data['gasId']=$gas['gasID'];
		$this->data['gunNo']=$order['oil_gun'];
		$this->data['couponId']=-1;
		$this->data['outerOrderId']=$order['order_no'];
		$this->data['amountGun']=$order['amount'];
		$this->data['token']=$this->supplier['token'];
		$re = $this->sendUrl('orderws/createOrder');
		if(isset($re['code']) && $re['code']==200){
			$orderId = $re['result']['orderId'];
			$amountPay = $re['result']['amountPay'];
			$o_pay_no = $re['result']['orderSn'];
			//更新到订单
			DB::name($this->tables->orders)->where("order_no",$order['order_no'])->update(['supplier_no'=>$orderId,'o_amountPay'=>$amountPay,'o_pay_no'=>$o_pay_no]);
			DB::name($this->tables->serviceOrder)->where("service_no",$order['order_no'])->update(['supplier_no'=>$orderId,'o_amountPay'=>$amountPay,'o_pay_no'=>$o_pay_no]);
			return true;
		}
		return $re['message'];
	}
	public function returnOrder($order){
		$this->setData();
		$this->data['orderSource']=$this->supplierCode;
		$this->data['orderId']=$order['supplier_no'];
		$re = $this->sendUrl('orderws/platformOrderQuery');
		if(isset($re['code']) && $re['code']==200){
			return $re['result'];
		}
		return false;
	}
	public function getGas($gas){
		return $this->getGases($gas['gasID']);
	}
	public function confirmOrder($order){
		$this->setData();
		$this->data['orderId']=$order['supplier_no'];
		$this->data['payAmount']=bcmul($order['o_amountPay'],100);
		$this->data['payStatus']=200;
		$this->data['payCode']=1290;
//		$this->data['token']=$this->supplier['token'];
		$re = $this->sendUrl('payCallbackApi');
		if(isset($re) && ($re==200 || $re==400)){
			return true;
		}
		return false;
	}
	public function pushGas($json){
		try {
			//接收上游推送油站更新通知
			$this->data = $json;
			if(is_string($json)) $this->data = json_decode($json,true);

			if($this->data){
				$sign = $this->data['sign'];
				$this->mkSign();
				if($sign != $this->data['sign']){
					w_log(0,"接口返回".$this->supplier['id'],"签名错误",'Hi/pushGas',json_encode($this->data));
					return '签名错误';
				}
				$this->addGas($this->data);
			}
			return '数据错误';
		}catch (\Exception $e){
			return '内部错误';
		}
	}
	public function pushOrder($json){
		try {
			//接收上游订单处理通知
			$this->data = $json;
			if(!is_array($json)) $this->data = json_decode($json,true);

			if($this->data){
				$sign = $this->data['sign'];
				$this->mkSign();
				if($sign != $this->data['sign']){
					$this->data['sign2']=$sign;
					w_log(0,"接口返回".$this->supplier['id'],"签名错误",'Hi/pushOrder',json_encode($this->data));
					return '签名错误';
				}
				return $this->data;
			}else{
				w_log(0,"接口返回".$this->supplier['id'],"数据错误",'Hi/pushOrder',json_encode($this->data));
				return '数据错误:2';
			}
		}catch (\Exception $e){
			w_log(0,"接口返回".$this->supplier['id'],"内部错误",'Hi/pushOrder',$e.error_get_last());
			return '内部错误';
		}
	}
	public function account(){
		$this->setData();
		$re = $this->sendUrl('openapi/account/queryAmount');
		if(isset($re['return_code']) && $re['return_code']=='000000'){
			return $re['return_data']['amount'];
		}
		return false;
	}
	public function getGases($gasID){
	    $log = new \app\Log("tuanyou/getGas");
		$this->setData();
		$this->data['gasIds']=$gasID;
		$this->data['platformType']=$this->supplierCode;
		$this->data['phone']=$this->mobile;
		$re = $this->sendUrl('gas/queryPriceByPhone');
		$log->write(['data'=>$re]);
		if(isset($re['code']) && $re['code']==200){
			if(!isset($re['result']) || count($re['result'])<1){
				DB::name($this->tables->gas)->where("fromID",2)->where("gasID",$gasID)->update(['status'=>2]);
				echojson([],1,'已下线');
			}
			foreach ($re['result'] as $v){
				$this->addGas($v,true);
			}
		}else{
			echojson([],1,$re['message']);
		}
		return false;
	}
	public function getGasList($cint=1){
	    $log = new \app\Log("tuanyou/getGasList");
		//获取全量油站列表
		if($this->supplier['upPage']==0 && $this->supplier['upNum']>$cint)return false;
		if($this->supplier['upDate']==nowDate()){
			DB::name($this->tables->supplier)->where("id",$this->supplier['id'])->inc('upPage')->update();
			$this->supplier['upPage']++;
		}else{
			$this->supplier['upPage']=1;
			DB::name($this->tables->supplier)->where("id",$this->supplier['id'])->update(['upPage'=>1,'upDate'=>nowDate(),'upNum'=>1]);
		}
		$this->setData();
		$this->data['channelId']=$this->supplierCode;
		$this->data['requireLabel']=true;
		$re = $this->sendUrl('gas/queryGasInfoListOilNoNew');
		$log ->write(['data'=>$re]);
		if(isset($re['code']) && $re['code']==200){
			DB::name($this->tables->supplier)->where("id",$this->supplier['id'])->update(['upPage'=>0,'upNum'=>$cint+1]);
			if(!isset($re['result']) || count($re['result'])<1){
				echojson([],1,'无数据');
			}
			foreach ($re['result'] as $v){
				$this->addGas($v);
			}
		}else{
			echojson([],1,$re['message']);
		}
		return false;
	}





	protected function addGas($v,$onlyPrice=false){
		$gas = DB::name($this->tables->gas)->where("gasID",$v['gasId'])->find();
		if(!$onlyPrice){
			$d=[
				'fromID'=>$this->supplier['id'],
				'gasID'=>$v['gasId'],
				'name'=>$v['gasName'],
				'province'=>$v['provinceName'],//
				'province_id'=>$v['provinceCode'],
				'city'=>$v['cityName'],//
				'city_id'=>$v['cityCode'],
				'country'=>$v['countyName'],//
				'county_id'=>$v['countyCode'],
				'address'=>$v['gasAddress'],
				'logo_small'=>$v['gasLogoSmall'],
				'logo_big'=>$v['gasLogoBig'],
				'status'=>1,//能获取的都是再营业的
				'lat'=>$v['gasAddressLatitude'],
				'lng'=>$v['gasAddressLongitude'],
				'business_time'=>$v['businessHours'],
			];
			if($gas){
				$up = DB::name($this->tables->gas)->where("id",$gas['id'])->update($d);
			}else{
				$up = DB::name($this->tables->gas)->insertGetId($d);
				$gas['id']=$up;
			}
		}else{
			$up=false;
		}
		//处理价格和油枪
		$prices = $v['oilPriceList'];
		if($prices){
			//所有的油号全部禁用
			DB::name($this->tables->gasPrice)->where("gasID",$gas['id'])->update(['status'=>0]);
			$upPrice=false;
			foreach ($prices as $v2){
				//然后再挨着启用
//				if (!isset($v2['gunNos']) || count($v2['gunNos'])<1){
				if (1==2){
					//没有枪号
					continue;
				}else{
					$price = DB::name($this->tables->gasPrice)->where("gasID",$gas['id'])->where("oil_no",$v2['oilName'])->find();
					$addUp=[
						'oil_type'=>$v2['oilType'],
						'oil_no'=>$v2['oilName'],
						'oil_name'=>$v2['oilNo'],
						'price_yfq'=>$v2['priceYfq'],
						'price_gun'=>$v2['priceGun'],
						'price_official'=>$v2['priceOfficial'],
						'status'=>1
					];
					$guns=[];
					//全量数据没有枪号
					if(isset($v2['gunNos']) && count($v2['gunNos'])>0){
						foreach ($v2['gunNos'] as $v3){
							$guns[] = ['gun_no'=>$v3['gunNo']];
						}
					}
					$addUp['gun_nos']=json_encode($guns);
				}
				if($price){
					DB::name($this->tables->gasPrice)->where("id",$price['id'])->update($addUp);
					if($price['price_yfq']!=$addUp['price_yfq'] || $price['price_gun']!=$addUp['price_gun'] || $price['price_official']!=$addUp['price_official']){
						$upPrice=true;
					}
				}else{
					$addUp['gasID']=$gas['id'];
					DB::name($this->tables->gasPrice)->insertGetId($addUp);
				}
			}
			if($up  || $upPrice) DB::name($this->tables->gas)->where("id",$gas['id'])->inc('upNumber')->update();
		}
	}
	protected function setData(){
		$this->data = ['app_key'=>$this->appKey] ;
	}
	protected function getToken(){
		$api = "begin/platformLoginSimpleAppV4";
		$this->setData();
		$this->data['platformType']=$this->supplierCode;
		$this->data['platformCode']=$this->mobile;
		$re = $this->sendUrl($api);
		if($re && $re['code']==200){
			$this->supplier['token']=$re['result']['token'];
			$this->supplier['tokenTime']=time() + 3600*24*21;
			DB::name($this->tables->supplier)->update($this->supplier);
			return true;
		}else{
			return false;
		}
	}

	protected function start($supplier=[]){
		$this->supplier = $supplier;
		$this->apiUrl = $this->supplier['apiUrl'];
		$this->urlTest = $this->supplier['apiUrlTest'];
		if($this->supplier['develop']==-1) $this->develop=false;
		$this->develop?$this->url = $this->apiUrl:$this->url = $this->urlTest;
		$this->url = trim($this->url,"/")."/";
		$this->appKey = $this->supplier['appKey'];
		$this->secret = $this->supplier['secret'];
		$this->mobile = '15820412097';
// 		$this->mobile = '13258225999';
		$this->supplierCode = $this->supplier['supplierCode'];
		if($this->supplier['postType']==2){
			if($this->supplier['tokenTime']<time()){
				$this->getToken();
			}else{
				$this->token = $this->supplier['token'];
			}
		}
	}
	public function mkSign(){
		if(isset($this->data['sign'])) unset($this->data['sign']);
		ksort($this->data);
		$str='';
		!isset($this->data['timestamp'])?$this->data['timestamp']=''.nowMicrotime():'';
		foreach ($this->data as $k=>$v){
			if($k=='token') continue;
			if($v!='' && $v!=null && $v!=[]){
				if(is_array($v)){
					foreach ($v as $k2=>$v2){
						if($v2!='' && $v2!=null && $v2!=[]){
							$str .= $k2.$v2;
						}
					}
				}else{
					$str .= $k.$v;
				}
			}
		}
		$str=$this->secret.$str.$this->secret;
		$this->data['sign']=strtolower(md5($str));
	}
	protected function sendUrl($pra=''){
		if($pra=='') return [];
		$this->mkSign();
		$header = ['Content-Type: application/x-www-form-urlencoded'];
		if(isset($this->data['token'])){
			$token = $this->data['token'];
			unset($this->data['token']);
			$header[]="token: $token";
		}
		$url = $this->url.$pra."?".http_build_query($this->data);
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

		$t=0;
		if($t==1){
			curl_setopt($ch, CURLOPT_VERBOSE, true);
			curl_setopt($ch, CURLOPT_HEADER, true);
			$verbose = fopen('php://temp', 'w+');
			curl_setopt($ch, CURLOPT_STDERR, $verbose);
		}


		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		$response = curl_exec($ch);
        $log = new \app\Log("tuanyou/" . str_replace('/[\\/:*?"<>|\r\n]/', '_', $pra));
        $log->write([
            "url" => $this->url . $pra,
            "data" => $this->data,
            "header" => $header,
            "requ" => json_decode($response, true)
        ]);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$error = curl_error($ch);
		curl_close($ch);
		if ($error) {
			echo "cURL error: " . $error . "\n";
		} else {
			return json_decode($response,true);
		}
	}
}

?>